package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityCameraBinding;
import flc.ast.utils.CameraIndicator;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.WorkPathUtil;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    public static boolean sIsID;
    private int mIndicator;//拍照模式
    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private int shotTime = 0;//拍摄延迟
    private int selTime = 3000;//选择的延时时间
    private int number;//拍照倒计时
    private Handler mHandler;
    private int mRecordTime;//拍摄视频的时间
    private boolean isShoot = false;
    private boolean isDelay = false;//是否开启延时拍摄
    private int delayType = 0;//延时类型
    private boolean isTaken = false;//是否拍摄完成
    private Bitmap saveBitmap;
    private String savePath = "";


    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }

    @Override
    public void onBackPressed() {
        if (isTaken) {
            mDataBinding.tvCameraTitle.setText(getString(R.string.take_photo));
            mDataBinding.tvVideoNum.setVisibility(mIndicator == 1 ? View.VISIBLE : View.INVISIBLE);
            mDataBinding.tvCameraTitle.setVisibility(mIndicator == 1 ? View.INVISIBLE : View.VISIBLE);
            mDataBinding.ivCameraStart.setImageResource(mIndicator == 1 ? R.drawable.paishipin : R.drawable.paizhao);
            mDataBinding.cameraView.setVisibility(View.VISIBLE);
            mDataBinding.ivCameraImg.setVisibility(View.GONE);
            isTaken = false;
        } else {
            finish();
        }
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraDelay.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.tvDelayText1.setOnClickListener(this);
        mDataBinding.tvDelayText2.setOnClickListener(this);
        mDataBinding.tvDelayText3.setOnClickListener(this);

        mHandler = new Handler();
        mRecordTime = 0;

        mDataBinding.ivCameraDelay.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (isDelay) {
                    mDataBinding.llCameraDelay.setVisibility(View.VISIBLE);
                }
                return true;
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraFlash://闪光灯
                openFlash();
                break;
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivCameraDelay://延时拍摄
                openDelayShot();
                break;
            case R.id.tvDelayText1://3秒
                clearSelection();
                mDataBinding.tvDelayText1.setTextColor(Color.parseColor("#FFFFFF"));
                selTime = 3000;
                shotTime = selTime;
                mDataBinding.llCameraDelay.setVisibility(View.GONE);
                break;
            case R.id.tvDelayText2://5秒
                clearSelection();
                mDataBinding.tvDelayText2.setTextColor(Color.parseColor("#FFFFFF"));
                selTime = 5000;
                shotTime = selTime;
                mDataBinding.llCameraDelay.setVisibility(View.GONE);
                break;
            case R.id.tvDelayText3://10秒
                clearSelection();
                mDataBinding.tvDelayText3.setTextColor(Color.parseColor("#FFFFFF"));
                selTime = 10000;
                shotTime = selTime;
                mDataBinding.llCameraDelay.setVisibility(View.GONE);
                break;
            case R.id.ivCameraStart://开始拍摄
                if (isTaken && !sIsID) {
                    save();
                } else {
                    startShot();
                }
                break;
        }
    }

    @Override
    protected void initData() {
        List<String> tabs = Arrays.asList(getString(R.string.shot), getString(R.string.video), getString(R.string.id_photo));
        // 实现了 CameraIndicator.Tab 的对象
        List<CameraIndicator.Tab> tabList = new ArrayList<>();
        for (String tab : tabs) {
            tabList.add(() -> tab);
        }
        CameraIndicator.Tab[] map = tabList.toArray(new CameraIndicator.Tab[0]);
        // 将 tab 集合设置给 cameraIndicator，（binding.cameraIndicator 即 xml 布局里的控件）
        mDataBinding.cameraIndicator.setTabs(map);
        // 默认选中拍照
        mDataBinding.cameraIndicator.setCurrentIndex(sIsID ? 2 : 0);
        mDataBinding.cameraIndicator.setOnSelectedChangedListener((index, tag) -> {
            if (mDataBinding.cameraView.isTakingVideo()) return;
            mIndicator = index;
            mDataBinding.tvVideoNum.setVisibility(index == 1 ? View.VISIBLE : View.INVISIBLE);
            mDataBinding.tvCameraTitle.setVisibility(index == 1 ? View.INVISIBLE : View.VISIBLE);
//            mDataBinding.tvSel.setVisibility(index == 2 ? View.VISIBLE : View.INVISIBLE);
            mDataBinding.ivCameraStart.setImageResource(index == 1 ? R.drawable.paishipin : R.drawable.paizhao);
            mDataBinding.ivCameraIcon.setVisibility(index == 2 ? View.VISIBLE : View.INVISIBLE);
            if (index == 2) {
//                mDataBinding.tvSel.setText("已选：" + Constants.sIdPhotosBean.getName());
            }
            if (index == 1) {
                isShoot = false;
                mDataBinding.cameraView.setMode(Mode.VIDEO);
            } else {
                isShoot = true;
                mDataBinding.cameraView.setMode(Mode.PICTURE);
            }
        });
        //初始化相机
        initCameraView();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                //获取图片 去到预览界面
                isTaken = true;
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }
                result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        if (sIsID) {
                            IdPhotoPreviewActivity.sBitmap = bitmap;
                            startActivity(IdPhotoPreviewActivity.class);
                        } else {
                            mDataBinding.tvCameraTitle.setText(getString(R.string.preview));
                            saveBitmap = bitmap;
                            mDataBinding.ivCameraImg.setImageBitmap(saveBitmap);
                            mDataBinding.ivCameraStart.setImageResource(R.drawable.atupianbaocun);
                            mDataBinding.cameraView.setVisibility(View.GONE);
                            mDataBinding.ivCameraImg.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {
                //开始拍摄视频
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //视频拍摄结束
                mDataBinding.tvCameraTitle.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraTitle.setText(getString(R.string.preview));
                mDataBinding.tvVideoNum.setVisibility(View.GONE);
                mDataBinding.ivCameraStart.setImageResource(R.drawable.ashipinbaocun);
                mDataBinding.tvVideoNum.setText("00:00:00");
                mDataBinding.tvVideoNum.setBackgroundColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvVideoNum.setTextColor(Color.parseColor("#8C8C8C"));
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                isTaken = true;
                savePath = result.getFile().getPath();
                Glide.with(mContext).load(savePath).into(mDataBinding.ivCameraImg);
                mDataBinding.ivCameraStart.setImageResource(R.drawable.ashipinbaocun);
                mDataBinding.cameraView.setVisibility(View.GONE);
                mDataBinding.ivCameraImg.setVisibility(View.VISIBLE);
            }
        });
    }

    //开始拍摄
    private void startShot() {
        if (isShoot) {
            if (mDataBinding.cameraView.isTakingPicture()) return;
            //加个拍照延迟
            if (shotTime > 0) {
                delayNumber();//倒计时
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mDataBinding.cameraView.takePictureSnapshot();
                }
            }, shotTime);
        } else {
            if (mDataBinding.cameraView.isTakingVideo()) {
                mDataBinding.cameraView.stopVideo();
            } else {
                String filePath = FileUtil.generateFilePath(WorkPathUtil.WORK_DIR, ".mp4");
                if (filePath != null) {
                    //加个拍视频延迟
                    if (shotTime > 0) {
                        delayNumber();//倒计时
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                        }
                    }, shotTime);
                }
            }
        }
    }

    //倒计时
    private void delayNumber() {
        number = shotTime / 1000;
        new CountDownTimer(shotTime, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.tvCameraDelayText.setVisibility(View.VISIBLE);
                //millisUntilFinished / 1000 会有不可描述的问题
                mDataBinding.tvCameraDelayText.setText("" + number--);
            }

            @Override
            public void onFinish() {
                mDataBinding.tvCameraDelayText.setVisibility(View.GONE);
            }
        }.start();
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.sgdguan);
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.sgd);
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    //打开延时拍摄
    private void openDelayShot() {
        if (isDelay) {
            isDelay = false;
            shotTime = 0;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.djs);
            shotTipText(getString(R.string.delay_close));
            mDataBinding.llCameraDelay.setVisibility(View.GONE);
        } else {
            isDelay = true;
            shotTime = selTime;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.djskai);
            shotTipText(getString(R.string.delay_open));
        }
    }

    //显示提示文字
    private void shotTipText(String text) {
        mDataBinding.tvCameraTipText.setText(text);
        mDataBinding.tvCameraTipText.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mDataBinding.tvCameraTipText.setVisibility(View.GONE);
            }
        }, 500);
    }

    //开始拍摄视频
    private void startRecordTime() {
        mDataBinding.tvVideoNum.setBackgroundColor(Color.parseColor("#FF7D7D"));
        mDataBinding.tvVideoNum.setTextColor(Color.parseColor("#000000"));
        mDataBinding.ivCameraStart.setImageResource(R.drawable.aluzhizhong);
        mRecordTime = 0;
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
        mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄视频
    private void stopRecordTime() {
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mDataBinding.tvVideoNum.setText(TimeUtil.getHHmmss(mRecordTime * 1000L));
            mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

    //保存预览
    private void save() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        if (mIndicator == 0) {
                            //保存到相册
                            ImageUtils.save2Album(saveBitmap, Bitmap.CompressFormat.PNG);
                            //保存到历史作品
                            String filePath = FileUtil.generateFilePath(Content.myShotWork, ".png");
                            ImageUtils.save(saveBitmap, filePath, Bitmap.CompressFormat.PNG);
                        } else {
                            //保存到相册
                            FileP2pUtil.copyPrivateVideoToPublic(mContext, savePath);
                            //保存到历史作品
                            String filePath = FileUtil.generateFilePath(Content.myShotWork, ".png");
                            FileUtils.move(savePath, filePath);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    private void clearSelection() {
        mDataBinding.tvDelayText1.setTextColor(Color.parseColor("#BFBFBF"));
        mDataBinding.tvDelayText2.setTextColor(Color.parseColor("#BFBFBF"));
        mDataBinding.tvDelayText3.setTextColor(Color.parseColor("#BFBFBF"));
    }

}